/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jfonia.view.main.header;

import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import org.jfonia.connect5.basics.Observer;
import org.jfonia.view.main.LeadSheetPlayer;

/**
 *
 * @author Rik Bauwens
 */
public class InstrumentChooser extends JComboBox implements Observer, ActionListener
{
        private String requestedInstrument;
        private int actionCount;

        public InstrumentChooser()
        {
                super();
                actionCount = 1;
                setEnabled(false);
                requestedInstrument = null;
                LeadSheetPlayer.getInstance().addStateObserver(this);
        }

        public String getInstrument()
        {
                if(getSelectedItem() == null)
                        return "";
                return (String) getSelectedItem();
        }

        public synchronized void setInstrument(String instrument)
        {
                requestedInstrument = instrument;
                if(!isEnabled())
                        return;
                String foundInstrument = LeadSheetPlayer.getInstance().getInstrument(instrument);
                if(foundInstrument == null)
                        setEnabled(false);
                else
                {
                        setSelectedItem(foundInstrument);
                        if(!instrument.contentEquals(foundInstrument))
                                LeadSheetPlayer.getInstance().setInstrument(foundInstrument);
                }
        }

        //Auxiliary boolean to check whether the actionPerformed is actually an action
        //invoked by the user (when the component is initalised, when the itemlist
        //is cleared en when items are added, 'false' actions are thrown)
        public boolean isActionValid()
        {
                if(actionCount == 0)
                        return true;
                actionCount--;
                return false;
        }

        private synchronized void setInstruments(String[] instruments)
        {
                setEnabled(false);
                removeAllItems();
                actionCount++;
                
                if(instruments == null)
                        return;

                for(String instrument : instruments)
                        addItem(instrument);
                if(instruments.length > 0)
                        actionCount++;
                setEnabled(true);
        }

        public void onNotify(Object source)
        {
                setInstruments(LeadSheetPlayer.getInstance().getInstruments());
                if(requestedInstrument != null)
                        setInstrument(requestedInstrument);
        }
}
